// https://www.lintcode.com/problem/minimum-absolute-difference-in-bst/

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: the root
     * @return: the minimum absolute difference between values of any two nodes
     */
    public int getMinimumDifference(TreeNode root) {
        // Write your code here
        // 利用中序遍历排序，然后找最小绝对差。
        List<Integer> vals = new ArrayList<>();
        inOrder(root, vals);
        int ret = vals.get(vals.size() - 1) - vals.get(0);
        for (int i = 1; i < vals.size(); ++i) {
            int diff = vals.get(i) - vals.get(i - 1);
            if (diff < ret) {
                ret = diff;
            }
        }
        return ret;
    }
    
    protected void inOrder(TreeNode root, List<Integer> vals) {
        if (root != null) {
            if (root.left != null) {
                inOrder(root.left, vals);
            }
            vals.add(root.val);
            if (root.right != null) {
                inOrder(root.right, vals);
            }
        }
    }
}